package kr.co.graviti.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.graviti.common.application.MultipartUploadFileService;
import kr.co.graviti.common.model.FileMeta;
import kr.co.graviti.common.model.MultipartUploadFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploader {
	
	private static final Logger logger = LoggerFactory.getLogger(GlobalController.class);
	
	@Value("${common.default.upload.path}") private String prUploadPath;
	@Value("${common.upload.size}") private long uploadSize;
	@Value("${common.upload.allow_postfix}") private String uploadAllowPostfix;
	
	@Resource
	private MultipartUploadFileService multipartUploadFileService;
	
	private MultipartFile[] files;
	
	@RequestMapping(value="/uploader")
	public ModelAndView uploader(HttpServletRequest request
			, HttpServletResponse response) {
		
		logger.info("prUploadPath : " + prUploadPath);
		
		return new ModelAndView(new String("examples/uploader"));
	}
	
	@RequestMapping(value="/uploader_process")
	public ModelAndView uploaderProcess(HttpServletRequest request
			, HttpServletResponse response
			, @RequestParam(value="ulfile", required=true) MultipartFile ulfile) {
		
		MultipartUploadFile multipartUploadFile = new MultipartUploadFile();
		multipartUploadFile = multipartUploadFileService.regist("file",prUploadPath
				, uploadSize
				, uploadAllowPostfix
				, ulfile);
		
		return null;
	}
	
	@RequestMapping(value="/file/uploadStatus", method=RequestMethod.GET)
	@ResponseBody
	public List<FileMeta> uploadStatus() throws IllegalStateException, IOException {
		
		List<FileMeta> fileMetas = new ArrayList<FileMeta>();
		
		for (MultipartFile file : files) {
			File uploadFile = new File(prUploadPath, file.getOriginalFilename());
			file.transferTo(uploadFile);
			FileMeta fileMeta = new FileMeta(uploadFile.getAbsolutePath()
					, file.getSize()
					, 1000);
			System.out.println(uploadFile);
		}
		
		return fileMetas;
	}
	
	@RequestMapping(value="/examples/loading", method=RequestMethod.GET)
	public ModelAndView loading(HttpServletRequest request
			, HttpServletResponse response) {
		
		return new ModelAndView(new String("examples/loading"));
	}
	
	

}
